<template>
  <!-- 上传图片 -->
  <el-dialog
    class="upload-img-dialog"
    title="上传图片"
    :visible.sync="showDialog"
    width="50%"
    :before-close="handleClose"
  >
    <div class="flex align-top justify-center">
      <div class="flex-sub">
        <el-upload
          ref="upload"
          multiple
          drag
          action="#"
          :on-change="onChange"
          :file-list="fileList"
          :auto-upload="false"
          :http-request="uploadFn"
          :on-remove="handleRemove"
        >
          <div v-if="!previewUrl">
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </div>
          <el-image v-else :src="previewUrl" fit="scale-down" />
          <div slot="tip" class="el-upload__tip">
            <span class="text-red">文件名称需与SKU名称一致</span>
            只能上传jpg/png文件，且不超过50MB
          </div>
        </el-upload>
      </div>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="uploadFn">上 传</el-button>
    </span>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
export default {
  props: {
    showUploadImg: {
      type: Boolean,
      default: false
    },
    ruleForm: {
      type: Object,
      default: function() {
        return {}
      }
    },
    waybillId: {
      type: String,
      default: '#'
    },
    url: {
      type: String,
      default: '#'
    }
  },
  data() {
    return {
      fileList: [],
      previewUrl: ''
    }
  },
  computed: {
    showDialog: {
      get: function() {
        return this.showUploadImg
      },
      set: function(val) {
        this.$emit(`update:showUploadImg`, val)
      }
    }
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
          this.closeFn()
        })
        .catch(_ => {})
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      if (fileList.length === 0) {
        this.previewUrl = ''
      }
    },
    handlePreview(file) {
      console.log('handlePreview', file)
    },
    onChange(file, fileList) {
      this.fileList = fileList
      this.previewUrl = URL.createObjectURL(file.raw)
      console.log(
        '%cthis.ruleForm.coverFile: ',
        'color: MidnightBlue; background: Aquamarine;',
        this.previewUrl
      )
    },

    beforeUpload(file) {
      console.log('beforeUpload')

      const isJPG = file.type === 'image/jpeg'
      const isPng = file.type === 'image/png'
      if (!isJPG && !isPng) {
        this.$message.error('上传文件只能是jpg/png文件!')
        return false
      }
      const isLt50M = file.size / 1024 / 1024 < 50

      if (!isLt50M) {
        this.$message.error('上传文件大小不能超过 50MB!')
        return false
      }
      return true
    },

    closeFn() {
      this.fileList = []
      this.previewUrl = ''
      const rule = {
        coverFile: '',
        coverUrl: ''
      }
      this.$emit(`update:ruleForm`, rule)
      this.$emit(`update:showUploadImg`, false)
    },

    async uploadFn(params) {
      console.log('params', params)
      console.log('this.fileList :>> ', this.fileList)

      if (this.fileList.length === 0) {
        this.$message.error('请上传文件')
        return false
      }

      this.$store.dispatch('app/toggleDialog', true)
      // 通过 FormData 对象上传文件
      const formData = new FormData()
      // 通过 FormData 对象上传文件
      for (const i of this.fileList) {
        if (await this.beforeUpload(i.raw)) {
          formData.append('file', i.raw)
        }
      }
      formData.append('waybillId', this.waybillId)

      const data = await request({
        url: this.url,
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      console.log('data', data)
      console.log('data.code', data.code)

      if (data.code === 200) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.$emit(`getImgUrl`, data.data)
        this.previewUrl = ''
        this.$emit(`update:showUploadImg`, false)
        this.fileList = []
      } else {
        this.$message.error('上传失败')
        this.fileList = []
      }
      this.$store.dispatch('app/toggleDialog', false)
    }
  }
}
</script>

<style lang="scss">
.upload-img-dialog {
  .el-upload {
    width: 100%;
    .el-upload-dragger {
      width: 100%;
    }
  }
  .upload-img {
    height: calc(100% - 46px);
    .el-upload {
      width: 100%;
      height: 100%;
      .el-upload-dragger {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>

<style scoped>
/deep/.el-upload-dragger {
  height: auto;
  min-height: 180px;
  max-height: 500px;
}
</style>
